package com.example.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.common.exception.BusinessException;
import com.example.admin.common.util.PasswordEncoder;
import com.example.admin.common.util.UserContext;
import com.example.admin.entity.SysRole;
import com.example.admin.entity.SysUser;
import com.example.admin.entity.SysUserRole;
import com.example.admin.mapper.SysRoleMapper;
import com.example.admin.mapper.SysUserMapper;
import com.example.admin.mapper.SysUserRoleMapper;
import com.example.admin.model.dto.SysUserRequest;
import com.example.admin.model.dto.UserDTO;
import com.example.admin.model.dto.PasswordDTO;
import com.example.admin.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private SysRoleMapper roleMapper;
    
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    private static final String DEFAULT_PASSWORD = "123456";

    @Override
    public IPage<SysUser> getUserPage(SysUserRequest request) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(StringUtils.hasText(request.getUsername()), SysUser::getUsername, request.getUsername());
        wrapper.like(StringUtils.hasText(request.getNickname()), SysUser::getNickname, request.getNickname());
        wrapper.eq(request.getStatus() != null, SysUser::getStatus, request.getStatus());

        // 按创建时间降序排序
        wrapper.orderByDesc(SysUser::getCreateTime);
        
        return userMapper.selectPage(request.getPage(), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(UserDTO userDTO) {
        // 检查用户名是否已存在
        Integer count = userMapper.selectCount(
            new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, userDTO.getUsername())
        );
        if (count > 0) {
            throw new BusinessException("用户名已存在");
        }

        // 创建用户
        SysUser user = new SysUser();
        user.setUsername(userDTO.getUsername());
        user.setPassword(PasswordEncoder.encode(userDTO.getPassword()));
        user.setNickname(userDTO.getNickname());
        user.setStatus(userDTO.getStatus());
        userMapper.insert(user);
        log.info("创建用户成功: {}", user.getId());

        // 分配默认角色
        SysRole userRole = roleMapper.selectOne(
            new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getCode, "ROLE_USER")
        );
        if (userRole != null) {
            userRoleMapper.insert(new SysUserRole(user.getId(), userRole.getId()));
            log.info("分配默认角色成功: {} - {}", user.getId(), userRole.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UserDTO userDTO) {
        // 检查用户是否存在
        SysUser user = userMapper.selectById(userDTO.getId());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 更新用户信息
        user.setNickname(userDTO.getNickname());
        user.setStatus(userDTO.getStatus());
        userMapper.updateById(user);
        log.info("更新用户成功: {}", user.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long id) {
        // 检查用户是否存在
        SysUser user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 删除用户角色关联
        userRoleMapper.delete(
            new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, id)
        );
        log.info("删除用户角色关联成功: {}", id);

        // 删除用户
        userMapper.deleteById(id);
        log.info("删除用户成功: {}", id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(Long id) {
        // 检查用户是否存在
        SysUser user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 重置密码
        user.setPassword(PasswordEncoder.encode(DEFAULT_PASSWORD));
        userMapper.updateById(user);
        log.info("重置用户密码成功: {}", id);
    }

    @Override
    public SysUser getCurrentUser() {
        return userMapper.selectById(UserContext.getUser().getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProfile(UserDTO userDTO) {
        SysUser currentUser = getCurrentUser();
        
        // 更新昵称
        currentUser.setNickname(userDTO.getNickname());
        userMapper.updateById(currentUser);
        
        // 更新上下文中的用户信息
        UserContext.setUser(currentUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(PasswordDTO passwordDTO) {
        // 验证两次密码是否相同
        if (!passwordDTO.getNewPassword().equals(passwordDTO.getConfirmPassword())) {
            throw new BusinessException("两次输入的密码不一致");
        }

        // 验证原密码是否正确
        SysUser currentUser = getCurrentUser();
        if (!PasswordEncoder.matches(passwordDTO.getOldPassword(), currentUser.getPassword())) {
            throw new BusinessException("原密码不正确");
        }

        // 更新密码
        currentUser.setPassword(PasswordEncoder.encode(passwordDTO.getNewPassword()));
        userMapper.updateById(currentUser);
    }

    @Override
    public SysUser getUserById(Long id) {
        return userMapper.selectById(id);
    }
}